<?php

namespace App\Http\Controllers\Article;

use App\Http\Controllers\Controller;
use App\Models\Administrator;
use App\Models\Article;
use App\Models\Channel;
use Illuminate\Http\Request;
use Exception as AppException;
use Illuminate\Support\Facades\Storage;

class ArticleController extends Controller
{
    public function article(int $id){
        // 文章详细内容。
        return Article::find($id);
    }


    // ajax 分页
    private $model = Article::class;
    public function ajax()
    {
        $pid = Request::capture()->input("p", 0);
        $cid = Request::capture()->input("c", 0);
        try{
            // 创建
            $condition = [];
            if ($cid > 0) {
                $condition = ["categroy"=>intval($cid)];
            }

            $order = ['hits' => 'desc', 'created_at'=>'desc'];
            $limit = 10;

            $model = $this->model::where(
                array_merge($condition)
            );
            // 条件 where()
            /*foreach ($condition as $where) {
                if (count($where) == 0 ) continue;
                $model->where(...$where);
            }*/
            // 排序
            foreach ($order as $field => $value) {
                $model->orderBy($field, $value);
            }
            $data = $model->paginate($limit)->toArray();
            foreach ($data['data'] as $k=>$datum) {
                $thumbs = Storage::disk('public')->url($datum['thumbs']);
                $data['data'][$k]['thumbs'] = $thumbs;
            }
            return $data;
        } catch (\Exception $exception) {
            throw new AppException("查询数据失败:".$exception->getMessage(),10, $exception);
        }
    }

    /**
     * ****************************************
     * 通过channel找相关的文档。返回分页形式
     * 1、当channel为某一个父级分类，则递归找到child
     * 2、当channel为某一个单类节点，则加数组
     * ***************************************
     */
    public function ajaxByChannel()
    {
        $request = Request::capture();
        $child = Channel::find($request->input('c',1))->childNode();
        $map = count($child) > 0 ? $child : [$request->input('c',1)];
        $article = Article::whereIn( 'categroy', $map)->paginate(10)->toArray();
        foreach ($article['data'] as $k => $v){
            $article['data'][$k]['authorName'] = Administrator::find($v['author'])->name;
            $article['data'][$k]['links'] = route('article.detail',['id' => $v['id']]);
        }

        return view('home.ajax_channel', compact('article'));
    }
}
